package org.jwos.platform.service.internal;

import java.util.ArrayList;
import java.util.List;

import org.jwos.platform.domain.Plugin;
import org.jwos.platform.service.PluginManager;

public class StubPluginManager implements PluginManager {
	
	private List<Plugin> systemPlugins = new ArrayList();
	
	private List<Plugin> programPlugins = new ArrayList();
	
	private List<Plugin> settingPlugins = new ArrayList();

	public List<Plugin> getProgramPlugins() {
		return this.programPlugins;
	}

	public List<Plugin> getSettingPlugins() {
		return this.settingPlugins;
	}

	public List<Plugin> getSystemPlugins() {
		return this.systemPlugins;
	}

	public void registerPlugin(Plugin plugin) {
		
		if(this.getPluginById(plugin)!=null){
			return;
		}
		
		switch (plugin.getType()) {
		case Plugin.TYPE_SYSTEM:
			this.systemPlugins.add(plugin);
			this.sort(this.systemPlugins);
			break;
		case Plugin.TYPE_PROGRAM:
			this.programPlugins.add(plugin);
			this.sort(this.programPlugins);
			break;
		case Plugin.TYPE_SETTING:
			this.settingPlugins.add(plugin);
			this.sort(this.settingPlugins);
			break;
		}

	}

	public void unregisterPlugin(Plugin plugin) {		
		List<Plugin> list = null;
		
		switch (plugin.getType()) {
		case Plugin.TYPE_SYSTEM:
			list = this.systemPlugins;
			break;
		case Plugin.TYPE_PROGRAM:
			list = this.programPlugins;
			break;
		case Plugin.TYPE_SETTING:
			list = this.settingPlugins;
			break;
		}
		
		for(int i=0;i<list.size();i++) {
			if(list.get(i).getId().equals(plugin.getId())) {
				list.remove(i);
				break;
			}
		}
	}
	
	private Plugin getPluginById(Plugin plugin) {
		Plugin found = null;
		
		List<Plugin> list = null;		
		switch (plugin.getType()) {
		case Plugin.TYPE_SYSTEM:
			list = this.systemPlugins;
			break;
		case Plugin.TYPE_PROGRAM:
			list = this.programPlugins;
			break;
		case Plugin.TYPE_SETTING:
			list = this.settingPlugins;
			break;
		}
		
		for(int i=0;i<list.size();i++) {
			if(list.get(i).getId().equals(plugin.getId())) {
				found = list.get(i);
				break;
			}
		}
		
		return found;
	}
	
	private void sort(List<Plugin> list) {
		for(int i=0;i<list.size();i++) {
			for(int j=i+1;j<list.size();j++) {
				if(list.get(i).getOrder()>list.get(j).getOrder()) {
					Plugin temp = list.get(i);
					list.set(i, list.get(j));
					list.set(j, temp);
				}
			}
		}
	}
}
